<template>
  <div class="cofirm-buy-view">
    <!-- 顶部导航栏 -->
    <div class="top-nav">
      <van-nav-bar title="确认订单" left-arrow @click-left="onClickLeft" />
    </div>
    <!-- 顶部消息通知 -->
    <div class="top-tip">
      <van-notice-bar mode="closeable"
        >由于疫情原因，部分地区发货速度可能会存在一定延期，给您带来不便，敬请谅解</van-notice-bar
      >
    </div>
    <!-- 商品消息 -->
    <div class="content">
      <div class="add-address">
        <van-contact-card
          type="add"
          add-text="添加新地址"
          @click="addAddress"
          v-if="myAdress.length == 0"
        />
        <van-contact-card
          type="edit"
          :name="myAdress[addressIndex].name"
          :tel="myAdress[addressIndex].tel"
          @click="editAddress"
          v-if="myAdress.length > 0"
        />
      </div>
      <div class="goods-msg" v-if="confirmData.length > 0">
        <div
          class="content-list"
          v-for="item in confirmData"
          :key="item.createTime"
        >
          <van-card
            :num="item.num"
            :price="item.price + '.00'"
            :desc="item.version + ' ' + item.color"
            :title="item.name"
            :thumb="item.img.img"
          />
        </div>
      </div>
      <div class="goods-price-msg">
        <div
          class="goods-totalprice"
          v-for="(item, index) in goodsPriceMsgData"
          :key="index"
          @click="useDiscount(index)"
        >
          <div class="left">{{ item.left }}</div>
          <div class="right">
            <div
              class="right-left"
              :class="{ disable: item.right == '无可用' }"
            >
              {{ item.right }}
            </div>
            <div class="right-right" v-if="item.right == '无可用'">
              <van-icon name="arrow" />
            </div>
          </div>
        </div>
      </div>
      <div class="ticket">
        <div class="ticket-title">发票</div>
        <div class="ticket-tip">
          个人电子发票-个人 <van-icon name="arrow" />
        </div>
      </div>
    </div>
    <!-- 底部付款 -->
    <van-submit-bar
      v-if="totalPrice != null && confirmData.length > 0"
      :price="totalPrice * 100"
      :label="'共' + confirmData.length + '件，合计：'"
      button-text="去付款"
      @submit="goToBuyView"
    >
    </van-submit-bar>
    <!-- 增加地址弹出层 -->
    <van-popup
      round
      v-model="popupShow"
      closeable
      close-icon="close"
      position="bottom"
      :style="{ height: '70%' }"
    >
      <van-address-edit
        :area-list="areaList"
        show-postal
        show-delete
        show-set-default
        show-search-result
        :address-info="AddressInfo"
        :search-result="searchResult"
        :area-columns-placeholder="['请选择省', '请选择市', '请选择区/县']"
        @save="onSave"
        @delete="onDelete"
      />
    </van-popup>
    <!-- 编辑地址弹出层 -->
    <van-popup
      round
      v-model="popupShow2"
      closeable
      close-icon="close"
      position="bottom"
      :style="{ height: '70%' }"
    >
      <van-address-list
        v-model="chosenAddressId"
        :list="myAdress"
        default-tag-text="默认"
        @add="addAddress"
        @edit="onEdit"
        @select="selectAddress"
      />
    </van-popup>
    <!-- 优惠券单元格 -->
    <van-coupon-cell
      :coupons="coupons"
      :chosen-coupon="chosenCoupon"
      @click="showList = true"
    />
    <!-- 优惠券列表 -->
    <van-popup
      v-model="showList"
      round
      position="bottom"
      style="height: 90%; padding-top: 4px"
    >
      <van-coupon-list
        :coupons="coupons"
        :chosen-coupon="chosenCoupon"
        :disabled-coupons="disabledCoupons"
        @change="onChange"
        @exchange="onExchange"
      />
    </van-popup>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { areaList } from "@vant/area-data";
import { dateFtt } from "@/utils/timeformat";
const coupon = {
  available: 1,
  condition: "无使用门槛\n最多优惠12元",
  reason: "",
  value: 150,
  name: "优惠券名称",
  startAt: 1489104000,
  endAt: 1514592000,
  valueDesc: "1.5",
  unitDesc: "元",
};

export default {
  name: "CofirmBuyView",
  data() {
    return {
      //商品信息div数据
      goodsPriceMsgData: [
        {
          left: "商品总价",
          right: "¥29",
        },
        {
          left: "优惠券",
          right: "无可用",
        },
        {
          left: "礼品卡",
          right: "无可用",
        },
        {
          left: "现金券",
          right: "无可用",
        },
        {
          left: "红包",
          right: "无可用",
        },
        {
          left: "运费",
          right: "包邮",
        },
      ],
      //商品数据
      confirmData: [],
      //总价
      totalPrice: null,
      //弹出层状态
      popupShow: false,
      popupShow2: false,
      //组件地址绑定数据
      areaList,
      searchResult: [],
      //地址数据
      myAdress: [],
      //选中地址的id
      chosenAddressId: 1,
      //添加地址的id
      addressId: 0,
      //选中地址的index
      addressIndex: 0,
      //初始化新增地址栏
      AddressInfo: {},
      //地址编辑状态
      isEdit: false,
      //生成订单
      orderData: [],
      //避免重复添加同一个订单的id
      orderIdArr: [],
      //优惠券
      chosenCoupon: -1,
      coupons: [coupon],
      disabledCoupons: [coupon],
      showList: false,
    };
  },
  computed: {
    // ...mapState(['confirmData','totalPrice'])
  },
  activated() {
    let data = JSON.parse(localStorage.getItem("confirmData"));
    this.confirmData = data.data;
    this.totalPrice = data.totalPrice;
    this.goodsPriceMsgData[0].right = data.totalPrice;
    let myAdress = JSON.parse(localStorage.getItem("myAdress"));
    if (!myAdress) {
      localStorage.setItem("myAdress", JSON.stringify(this.myAdress));
    } else {
      this.myAdress = myAdress;
    }
    let orderData = JSON.parse(localStorage.getItem("orderData"));
    if (!orderData) {
      localStorage.setItem("orderData", JSON.stringify(this.orderData));
    } else {
      this.orderData = orderData;
    }
  },
  methods: {
    // 返回上一级路由
    onClickLeft() {
      this.$router.go(-1);
    },
    // 增加地址
    addAddress() {
      this.popupShow = true;
      this.AddressInfo = {};
    },
    // 跳转付款页面
    goToBuyView() {
      let id = dateFtt("yyyy-MM-dd hh:mm:ss", new Date());
      this.orderData.push({
        data: JSON.parse(localStorage.getItem("confirmData")).data,
        id,
        totalPrice: this.totalPrice,
      });
      localStorage.setItem("myAdress", JSON.stringify(this.myAdress));
      localStorage.setItem("orderData", JSON.stringify(this.orderData));
      this.$router.push({ name: "BuyView" });
    },
    //保存地址
    onSave(content) {
      if (!this.isEdit) {
        if (this.myAdress.length == 0) {
          content.id = this.myAdress.length + 1;
          content.address =
            content.province +
            content.city +
            content.county +
            " " +
            content.addressDetail;
          this.myAdress.unshift(content);
          localStorage.setItem("myAdress", JSON.stringify(this.myAdress));
          this.$toast.success("添加地址成功");
        } else {
          let telArr = [];
          this.myAdress.forEach((item) => {
            telArr.push(item.tel);
          });
          if (telArr.indexOf(content.tel) == -1) {
            content.id = this.myAdress.length + 1;
            content.address =
              content.province +
              content.city +
              content.county +
              " " +
              content.addressDetail;
            this.myAdress.unshift(content);
            localStorage.setItem("myAdress", JSON.stringify(this.myAdress));
            this.$toast.success("添加地址成功");
          } else {
            this.$toast("相同的手机号已存在");
          }
        }
      } else {
        this.myAdress.forEach((item, index) => {
          if (item.tel == this.AddressInfo.tel) {
            this.myAdress[index] = content;
            this.$forceUpdate();
            this.$toast.success("修改成功");
            this.isEdit = false;
          }
        });
        localStorage.setItem("myAdress", JSON.stringify(this.myAdress));
      }
      this.popupShow = false;
    },
    //删除地址
    onDelete(content) {
      this.myAdress.forEach((item, index) => {
        if (item.tel == content.tel) {
          this.myAdress.splice(index, 1);
        }
      });
      this.popupShow = false;
      localStorage.setItem("myAdress", JSON.stringify(this.myAdress));
    },
    //编辑地址
    editAddress() {
      this.popupShow2 = true;
    },
    //有地址列表后的弹出层编辑事件
    onEdit(item) {
      this.isEdit = true;
      this.popupShow = true;
      this.AddressInfo = {
        id: item.id,
        name: item.name,
        tel: item.tel,
        postalCode: item.postalCode,
        areaCode: item.areaCode,
        addressDetail: item.addressDetail,
        isDefault: item.isDefault,
      };
    },
    //选择地址
    selectAddress(item, index) {
      this.addressIndex = index;
    },
    //优惠券
    useDiscount(index) {
      if (index == 1) {
        this.showList = true;
      }
    },
    onChange(index) {
      this.showList = false;
      this.chosenCoupon = index;
      this.goodsPriceMsgData[1].right=`-${coupon.valueDesc}`
      this.totalPrice=this.totalPrice-Number(coupon.valueDesc)
      this.goodsPriceMsgData[0].right=this.totalPrice
    },
    onExchange(code) {
      this.coupons.push(coupon);
    },
  },
};
</script>

<style lang="scss" scoped>
.cofirm-buy-view {
  background-color: #f5f5f5;
  width: 100vw;
  height: 100vh;
  position: fixed;
  overflow: auto;
  top: 0;
  left: 0;
  z-index: 20;
  padding-top: 50px;
  .top-nav {
    width: 100vw;
    height: 50px;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 10;
  }
  .add-address {
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
    overflow: hidden;
  }
  ::v-deep .van-contact-card__value {
    font-weight: 600;
    font-size: 16px;
  }
  ::v-deep .van-submit-bar__bar {
    .van-button--danger {
      background: rgb(254, 117, 36);
    }
  }
  ::v-deep .van-submit-bar__text {
    position: absolute;
    left: 20px;
    .van-submit-bar__price {
      color: rgb(254, 117, 36);
      font-weight: 600;
    }
  }
  ::v-deep .van-card {
    background-color: #fff;
  }
  .content {
    padding: 10px 10px 110px;
    .goods-msg {
      border-radius: 8px;
      overflow: hidden;
      margin-top: 10px;
      text-align: left;
      ::v-deep .van-card__title {
        font-weight: 600;
        font-size: 14px;
      }
      ::v-deep .van-card__price {
        color: rgb(254, 117, 36);
        font-weight: 600;
        font-size: 18px;
        .van-card__price-integer {
          font-size: 18px;
        }
        .van-card__price-currency {
          font-size: 15px;
          margin-right: 2px;
        }
      }
      .content-list {
        margin-bottom: 10px;
        &:last-of-type {
          margin-bottom: 0;
        }
      }
    }
    .goods-price-msg {
      border-radius: 8px;
      overflow: hidden;
      background-color: #fff;
      padding: 10px;
      margin-top: 15px;

      .goods-totalprice {
        height: 40px;
        line-height: 40px;
        display: flex;
        justify-content: space-between;
        .right {
          display: flex;
          .right-left {
            &.disable {
              color: #888;
            }
          }
        }
      }
    }
    .ticket {
      height: 40px;
      background-color: #fff;
      border-radius: 8px;
      padding: 0 10px;
      line-height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 10px;
    }
  }
  ::v-deep .van-address-edit {
    padding: 35px 10px 0;
  }
  ::v-deep .van-radio-group {
    margin-top: 25px;
    .van-address-item__name {
      margin-bottom: 0;
    }
  }
}
</style>